<?php
include ('../config/config.php');
include ('../includes/eXist.php');
header ("Content-Type:text/xml");

$list = $_GET['list'];
$code = "ref";
if($list == "sector") {
	$code = "code";
}

//Get Ref
function getRef($node) {
	global $code;
	if(strlen(trim($node->id[0])) > 0) {
		return (string)$node->id[0];
	} else {
		return "tmp_".strtolower(str_replace(array("."),"",str_replace(array(" ",","),"_",(string)$node)));
	}
}



//Fetch Distinct
function fetchDistinct($list) {
global $code;
$my_exist_db = EXIST_DB;
$my_filename	= $list;
$position 		= strpos($list,'[');
if ( $position > 0 )
	$my_filename = substr($list,0,$position);
//echo $my_exist_db;
$query = <<<EOF
		xquery version "1.0";
		declare option exist:serialize "method=xml media-type=text/xml omit-xml-declaration=no";

let \$mydoc:=doc('/db/iAG/cache/_$my_filename.xml')
return 
<results> 
{\$mydoc//item} 
</results>
		
EOF;

	try
	  {
	  		//error_log($query);
	  		//error_log("FILENAME IS: $my_filename !!!!");
	  		
	        $db = new eXist();
	
	        # Connect
	        $db->connect() or die ($db->getError());
		
	        # XQuery execution
	        //$db->setDebug(TRUE);
	        $db->setHighlight(FALSE);
	        
	        $result = $db->xquery($query) or die ($db->getError());
	        
			$xml = simplexml_load_string($result['XML']);
			//echo $query;
			// error_log("ANSWER: ".print_r($result,true));
			foreach($xml->children() as $node) {
				//error_log($node->id[0]." => ".$node->label[0]);
				if ( isset($node->label) && strlen($node->label[0])>0 )
					$out_list[getRef($node)] = array("code" =>(string)($node->id[0]), "name"=>(string)($node->label[0]));	
			}
			
			return $out_list;
	}
	catch( Exception $e )
	{
	     die($e);
	}
}
;

//Caching functions
$filename = CACHE_FOLDER."list_cache_$list.cache";
$age = CACHE_LIFETIME ? CACHE_LIFETIME : 86400;

if (file_exists($filename)) {
  $mtime = filemtime($filename);
  $fileage = time() - $mtime;
  if ($fileage>$age) {
    $out_list = unserialize(file_get_contents($filename));
  } else {
    $out_list = fetchDistinct($list);
    //echo $list;
    file_put_contents($filename,serialize($out_list));
  }
} else {
    $out_list = fetchDistinct($list);
    //echo "2";
    file_put_contents($filename,serialize($out_list));
}


if($_GET['format']=="csv") {
	header("Content-type: text/csv");			
	echo "code,name\n";
	foreach($out_list as $code => $name) {
		echo $code.",\"".$name['name']."\"\n";
	}
} else {
	header("Content-type: application/json");
	echo json_encode(array("codelist"=>array("items"=>$out_list)));			
}

?>